package game.level;

import game.gfx.ImageReader;
import game.gfx.SpriteSheet;
import game.level.tiles.AnimatedTile;
import game.level.tiles.NormalTile;
import game.level.tiles.SolidTile;
import game.level.tiles.Tile;

public class Level extends ImageReader
{
	int width;
	int height;
	
	int VOID = 0xFF000000;				// id = 0
	int STONE = 0xFF555555;				// id = 1
	int GRASS = 0xFF00FF00;				// id = 2
	int WOOD = 0xFF987849; 				// id = 3
	int WATER = 0xFF3D6DFF;				// id = 4
	int ANIMATED_WATER = 0xFF0000FF; 	// id = 5
	int LEAVES = 0xFF1B381B;			// id = 6
		
	int[][] levelColour;
	int[][] levelPixels;
	Tile[][] levelTiles;
	
	public Level(String path, SpriteSheet sheet)
	{
		super(path);	
		
		width = getWidth();
		height = getHeight();
		
		levelTiles = new Tile[width][height];
		
		levelColour = getPixelData();
		
		for (int y = 0; y < height; y++)
		{
			for (int x = 0; x < width; x++)
			{
				if (levelColour[x][y] == VOID)  levelTiles[x][y] = new NormalTile(0, sheet, 0, 0);
				if (levelColour[x][y] == STONE) levelTiles[x][y] = new SolidTile(1, sheet, 1, 0);
				if (levelColour[x][y] == GRASS) levelTiles[x][y] = new NormalTile(2, sheet, 2, 0);
				if (levelColour[x][y] == WOOD) levelTiles[x][y] = new NormalTile(3, sheet, 3, 0);
				if (levelColour[x][y] == WATER) levelTiles[x][y] = new NormalTile(4, sheet, 4, 0);
				if (levelColour[x][y] == ANIMATED_WATER) levelTiles[x][y] = new AnimatedTile(5, sheet, new int[][] {{0, 5}, {1, 5}, {2, 5}}, 700);
				if (levelColour[x][y] == LEAVES) levelTiles[x][y] = new NormalTile(6, sheet, 3, 1);
			}
		}
	}
	
	public Tile[][] getLevelTiles()
	{
		return levelTiles;		
	}
	
	public int[][] getLevelPixels()
	{
		levelPixels = new int[width * SpriteSheet.spriteDimension][height * SpriteSheet.spriteDimension];
		
		int[][] temp;
		temp = new int[8][8];
		
		int x0 = 0;
		int x1 = 0;
		int x2 = 0;
		int y0 = 0;
		int y1 = 0;
		int y2 = 0;
		
		for (y0 = 0; y0 < height; y0++)
		{
			for (x0 = 0; x0 < width; x0++)
			{
				temp = levelTiles[x0][y0].getTileData();
				
				for (y1 = 0; y1 < 8; y1++)
				{
					for (x1 = 0; x1 < 8; x1++)
					{
						levelPixels[x2 + x1][y2 + y1] = temp[x1][y1];
					}					
				}
				x2 += 8;
			}
			y2 += 8;
			x2 = 0;
		}
	
		return levelPixels;
	}
	
	public void tick()
	{
		for (int y = 0; y < height; y++)
		{
			for (int x = 0; x < width; x++)
			{
				if (levelTiles[x][y].getId() == 5)
				{
					levelTiles[x][y].tick();
				}
			}
		}
	}
}
